package edu.hrbeu.crc.controller;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import edu.hrbeu.crc.config.OssConfig;
import edu.hrbeu.crc.constant.ErrorConstant;
import edu.hrbeu.crc.pojo.result.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/common")
public class CommonController {

    private final OssConfig ossConfig;

    private final OSS ossClient;

    /**
     * 图片上传接口
     * @param file 传递的文件（参数名固定为"img"）
     * @return 图片的OSS访问路径
     */
    @PostMapping("/upload") // 路径和请求方式要求
    public Result<String> uploadImage(MultipartFile file) {
        // 1. 校验文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException(ErrorConstant.FILE_BE_EMPTY);
        }

        // 2. 生成唯一文件路径
        String originalFilename = file.getOriginalFilename();
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".")); // 提取后缀（如.jpg）
        String uniqueId = UUID.randomUUID().toString() + "_" + System.currentTimeMillis(); // UUID+时间戳保证唯一
        String dynamicDir = ossConfig.getDir() + LocalDate.now() + "/"; // 动态目录
        String ossFilePath = dynamicDir + uniqueId + fileSuffix; // 完整OSS路径

        // 3. 上传到OSS
        try {
            ossClient.putObject(
                    ossConfig.getBucket(),  // Bucket名称
                    ossFilePath,            // 唯一文件路径
                    file.getInputStream()   // 文件输入流
            );
        } catch (OSSException oe) {
            throw new RuntimeException(ErrorConstant.OSS_SERVICE_EXCEPTION + oe.getErrorMessage());
        } catch (ClientException ce) {
            throw new RuntimeException(ErrorConstant.CLIENT_CONNECTION_EXCEPTION + ce.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(ErrorConstant.FILE_READING_FAILED + "：" + e.getMessage());
        }

        // 4. 返回完整访问路径（host + ossFilePath）
        return Result.success(ossConfig.getHost() + "/" + ossFilePath);
    }
}
